package com.example.gateway.filter.pre;

import com.example.common.exception.BadJwtException;
import com.example.common.util.JwtUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by atom on 2017/11/29
 */
@Slf4j
@Component
public class JwtFilter extends ZuulFilter {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.key}")
    private String key;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        System.out.println("------------pre filter should-------------");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String uri = request.getRequestURI();
        System.out.println("request.method: " + request.getMethod());
        System.out.println("request.uri: " + request.getRequestURI());
        log.info("%s request to %s", request.getMethod(), uri);
        return !uri.equals("/auth/login");
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String authHeader = request.getHeader(tokenHeader);
        if (authHeader == null) {
            try {
                ctx.getResponse().sendError(405);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        if (authHeader.startsWith(tokenHead)) {
            final String authToken = authHeader.substring(tokenHead.length());
            String userName = JwtUtils.getUserNameFromToken(key, authToken);
            if (!JwtUtils.validate(key, authToken, userName)) throw new BadJwtException("Bad Jwt");
            ctx.addZuulRequestHeader("x-username", userName);
        }

        return null;
    }
}
